<!DOCTYPE html>
<html lang="zh-cmn-Hans">

<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta name="description" content="">
	<meta name="author" content="">
	<link rel="icon" type="image/png" sizes="16x16" href="/static/img/favicon.ico" />
	<title>数据质量检核平台</title>

	<link rel="stylesheet" type="text/css" href="/static/check/css/admin/bootstrap.min.css"/>
	<link rel="stylesheet" type="text/css" href="/static/check/css/admin/style.css"/>
	<link rel="stylesheet" type="text/css" href="/static/CodeMirror/lib/codemirror.css"/>
	<link rel="stylesheet" type="text/css" href="/static/CodeMirror/theme/eclipse.css"/>
	<link rel="stylesheet" type="text/css" href="/static/css/sweetalert.css"/>
	<link rel="stylesheet" type="text/css" href="/static/css/icons.css"/>
	<link rel="stylesheet" type="text/css" href='/static/zTree/css/zTreeStyle.css'>
	<link rel="stylesheet" type="text/css" href="/static/js/bootstrap/css/bootstrapValidator.min.css"/>
	<link rel="stylesheet" type="text/css" href="/static/css/bootstrap-select.min.css">


	<style>
		.modal.fade.in{
			top: 180px;
		}
		.wrapper {
			padding: 0 !important;
		}
		.table > thead > tr > th, .table > tbody > tr > th, .table > tfoot > tr > th, .table > thead > tr > td, .table > tbody > tr > td, .table > tfoot > tr > td {
			vertical-align: middle;
		}
		.btn-default:hover, .btn-default:focus, .btn-default:active, .btn-default.active, .open .dropdown-toggle.btn-default {
			background-color: unset;
			border-color: unset;
			color: unset;
		}
		.btn-default.active, .btn-default.focus, .btn-default:active, .btn-default:focus, .btn-default:hover, .open>.dropdown-toggle.btn-default {
			background-color: unset;
			border-color: unset;
			color: unset;
		}
		.popover{
			max-width: 100%;
		}

		.bootstrap-select {
			width: 100% !important;
		}
		.CodeMirror {
			height: 200px !important;
		}
		.ibox-content .row {
			padding: 5px 0 !important;
		}
		.ibox-content .title {
			line-height: 30px;
			font-size: 16px;
			font-weight: 700;
			color: #676a6c;
			text-align: center;
		}
		.submit-btn {
			float: right;
			height: 80px;
			line-height: 80px;
		}
		.submit-btn button {
			width: 100px;
			height: 40px;
			font-size: 14px;
			margin-left: 20px;
		}
		#form {
			height: 80px;
		}
		.form-layout {
			display: flex;
			align-items: center;
		}
		.form-layout form {
			flex: 1;
		}
		.form-layout .form-group {
			width: 220px;
		}
		.form-layout label {
			width: 60px;
		}
		.form-group {
			margin-right: 25px;
		}
		.rule-wrapper .form-group {
			margin-right: 6px;
		}
		.inline-block {
			display: inline-block;
		}
		.rule-wrapper {
			display: flex;
			flex-direction: row;
			background: #f3f3f4;
		}
		.rule-wrapper-left, .rule-wrapper-right {
			margin: 10px;
		}
		.rule-wrapper-left {
			flex: 4;
		}
		.rule-wrapper-right {
			flex: 3;
		}
		.rule-wrapper-left .form-group, .rule-wrapper-right .form-group {

		}
		.rule-wrapper-left>div, .rule-wrapper-right>div {
			padding: 5px;
			margin-bottom: 10px;
			background: #fff;
		}
		.order {
			line-height: 24px;
		}
		#data_tree_wrapper {
			display: none;
			position: absolute;
			min-width: 200px;
			min-height: 300px;
			border-radius: 3px;
			box-shadow: 0 0 3px rgba(86, 96, 117, 0.7);
			background: #fff;
			z-index: 100;
		}
	</style>
</head>

<body onload="OnLoad();">
	<!-- head star -->
	<!--<div class="tnav row wrapper border-bottom white-bg page-heading">-->
		<!--<div class="col-sm-4">-->
			<!--<h2 class="fl" style="color: #007bff;font-size: 21px;font-weight:500">数据质量检核规则库</h2>-->
			<!--<ol class="breadcrumb fl">-->
				<!--<li><a href="../../data/index">主页</a></li>-->
				<!--<li><strong>检核规则库</strong></li>-->
			<!--</ol>-->
		<!--</div>-->
	<!--</div>-->
	<!-- head end -->

	<!-- table star -->
	<div class="row">
		<div class="wrapper animated fadeInUp">
			<div class="ibox" style="margin-bottom: 40px;">
				<form id="form" class="navbar-form form-inline">
					<div style="float: left;">
						<div style="display: flex;margin-bottom: 12px;">
							<div class="form-group">
								<div class="inline-block">
									<label>规则名称</label>
								</div>
								<div class="inline-block">
									<input class="form-control" id="note" name="note" type="text" autocomplete="off" style="width: 240px">
								</div>
							</div>
							<div class="form-group">
								<div class="inline-block">
									<label>目标表</label>
								</div>
								<div class="inline-block">
									<input class="form-control" id="target_table" name="target_table" type="text" autocomplete="off">
								</div>
							</div>
							<div class="form-group">
								<div class="inline-block">
									<label>数据标准</label>
								</div>
								<div class="inline-block">
									<input class="form-control" id="check_item" name="check_item" type="text" autocomplete="off">
									<div id="data_tree_wrapper">
										<ul id="data_tree" class="ztree"></ul>
									</div>
								</div>
							</div>
							<!--<div class="form-group">-->
							<!--<label>目标表</label>-->
							<!--<input id="target_table" type="text" class="form-control">-->
							<!--</div>-->
						</div>
						<div style="display: flex;">
							<div class="form-group">
								<div class="inline-block">
									<label>是否风险集市</label>
								</div>
								<div class="inline-block">
									<select class="selectpicker form-control" id="risk_market" name="risk_market">
										<option value="是">是</option>
										<option value="否">否</option>
									</select>
								</div>
							</div>
							<div class="form-group">
								<div class="inline-block">
									<label>问题分类</label>
								</div>
								<div class="inline-block">
									<select class="selectpicker form-control" id="problem_type" name="problem_type" type="text">
										<option>-- 请选择 --</option>
									</select>
								</div>
								<i class="fa fa-question-circle" data-toggle="popover"
								   style="color: #ffab00;font-size:15px;"></i>
							</div>
							<div class="form-group">
								<div class="inline-block">
									<label>源系统数据库</label>
								</div>
								<div class="inline-block">
									<select class="selectpicker form-control" id="db" name="db"></select>
								</div>
							</div>
							<div class="form-group">
								<div class="inline-block">
									<label>状态</label>
								</div>
								<div class="inline-block">
									<select class="selectpicker form-control" id="status" name="status">
										<option value="已启用">已启用</option>
										<option value="已停用">已停用</option>
									</select>
								</div>
							</div>
						</div>
					</div>
					<div class="form-group submit-btn">
						<button onclick="Commit();" class="btn btn-primary btn-sm">
							<i class="fa fa-check-square-o"></i> 提交
						</button>
					</div>
				</form>

				<div class="row ibox-content">
					<div class="row">
						<div class="col-md-6 title">问题数据</div>
						<div class="col-md-6 title">总数据</div>
					</div>
					<div class="rule-wrapper">
						<div class="rule-wrapper-left">
							<div index="0">
								<form class="navbar-form form-inline">
									<div class="form-group">
										<div class="inline-block">
											<label>序号: </label>
										</div>
										<div class="inline-block order">1</div>
									</div>
									<div class="form-group">
										<div class="inline-block">
											<label>子规则名</label>
										</div>
										<div class="inline-block">
											<input class="form-control" name="t_name" type="text" autocomplete="off">
										</div>
									</div>
									<!--<div class="form-group">-->
										<!--<div class="inline-block">-->
											<!--<label>字段名</label>-->
										<!--</div>-->
										<!--<div class="inline-block">-->
											<!--<input class="form-control" name="c_name" type="text" autocomplete="off">-->
										<!--</div>-->
									<!--</div>-->
									<div class="form-group">
										<div class="inline-block">
											<label>状态</label>
										</div>
										<div class="inline-block" style="width: 81px">
											<select class="selectpicker" name="effective">
												<option value="已启用">已启用</option>
												<option value="已停用">已停用</option>
											</select>
										</div>
									</div>
									<div class="form-group">
										<div class="inline-block">
											<label>绑定分母</label>
										</div>
										<div class="inline-block" style="width: 60px">
											<select class="selectpicker" name="denominator">
												<option value="1">1</option>
											</select>
										</div>
									</div>
									<div class="form-group" style="float: right; margin-right: 0;">
										<button class="btn btn-danger btn-sm" onclick="deleteItem(this, 'left')">删除</button>
									</div>
								</form>
								<div>
									<textarea class="form-control" name="code" type="text"></textarea>
								</div>
							</div>
							<div style="margin: 7px 0; text-align: center">
								<button class="btn btn-primary btn-sm" onclick="addLeftItem(this)">新增</button>
							</div>
						</div>
						<div class="rule-wrapper-right">
							<div index="0">
								<form class="navbar-form form-inline">
									<div class="form-group">
										<div class="inline-block">
											<label>序号: </label>
										</div>
										<div class="inline-block order">1</div>
									</div>
									<div class="form-group">
										<div class="inline-block">
											<label>子规则名</label>
										</div>
										<div class="inline-block">
											<input class="form-control" name="t_name" type="text" autocomplete="off">
										</div>
									</div>
									<!--<div class="form-group">-->
										<!--<div class="inline-block">-->
											<!--<label>字段名</label>-->
										<!--</div>-->
										<!--<div class="inline-block">-->
											<!--<input class="form-control" name="c_name" type="text" autocomplete="off">-->
										<!--</div>-->
									<!--</div>-->
									<div class="form-group">
										<div class="inline-block">
											<label>状态</label>
										</div>
										<div class="inline-block" style="width: 81px">
											<select class="selectpicker" name="effective">
												<option value="已启用">已启用</option>
												<option value="已停用">已停用</option>
											</select>
										</div>
									</div>
									<div class="form-group" style="float: right; margin-right: 0;">
										<button class="btn btn-danger btn-sm" onclick="deleteItem(this, 'right')">删除</button>
									</div>
								</form>
								<div>
									<textarea class="form-control" name="code" type="text"></textarea>
								</div>
							</div>
							<div style="margin: 7px 0; text-align: center">
								<button class="btn btn-primary btn-sm" onclick="addRightItem(this, 'right')">新增</button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<script src="/static/js/jquery/jquery.min.js"></script>
	<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
	<script src="/static/CodeMirror/lib/codemirror.js"></script>
	<script src="/static/CodeMirror/mode/sql.js"></script>
	<script src="/static/js/sweetalert.min.js"></script>
	<script src="/static/js/bootstrap/js/bootstrapValidator.min.js"></script>
	<script src="https://cdn.bootcss.com/bootstrap-select/2.0.0-beta1/js/bootstrap-select.min.js"></script>
	<script src='/static/zTree/js/jquery.ztree.core.min.js'></script>
	<script src='/static/zTree/js/fuzzysearch.js'></script>
	<script src='/static/zTree/js/jquery.ztree.exhide.min.js'></script>
	<script src='/static/zTree/js/jquery.ztree.exedit.js'></script>

	<script>
		let width = document.body.clientWidth;
		let company = "{{ source_system }}";
		let id = "{{ id }}";
		let delete_ids = [];
		let editor = {
			left: [],
			right: []
		};
		let setting = {
			data: {
				key: {
					title:"t"
				},
				simpleData: {
					enable: true
				}
			},
			callback: {
				onClick: onNodeClick
			},
		};

		$(document).ready(function () {
			QueryDB();
			getTree();
			setPopover();
			getProblemType(() => {
				if (id == 'null') {	// 新建
					let leftEditor = initEditor($('.rule-wrapper-left textarea')[0]);
					let rightEditor = initEditor($('.rule-wrapper-right textarea')[0]);
					editor.left.push(leftEditor);
					editor.right.push(rightEditor);
				} else {	// 更新
					queryDetail();
				}
			});

			$('#check_item').click(function() {
				$('#data_tree_wrapper').css('display', 'block');
			});
			$('#check_item').blur(function() {
				$('#data_tree_wrapper').css('display', 'none');
			});
			$("#data_tree_wrapper").on("mousedown ", function () {
				event.preventDefault();
			});
		});

		function onNodeClick(event, treeId, treeNode, clickFlag) {
			if (!treeNode.isParent) {
				$('#check_item').blur(function() {
					$('#data_tree_wrapper').css('display', 'none');
				});
				$('#check_item').val(treeNode.name);
				$('#check_item').attr('pk_id', treeNode.pk_id);
				$('#data_tree_wrapper').css('display', 'none');
			}
		}

		// 填充现有检核规则信息
		function OnLoad(){
			$(".selectpicker").selectpicker({
				noneSelectedText: '-- 请选择 --' //默认显示内容
			});

			if(id == "null"){
				$("#page-title").html(company + "新增检核规则");
			} else{
				$("#page-title").html(company + "修改检核规则");
			}
		}

		// 获取数据标准的树
		function getTree() {
			$.ajax({
				type: "GET",
				url: "../../api/datastandard/query/index",
				dataType: "json",
				success: function (result) {
					if (result.stat === 200) {
						result.data.forEach(v => {
							v.isParent = v.is_dir;
						});
						$.fn.zTree.init($("#data_tree"), setting, result.data);
						fuzzySearch('data_tree', '#check_item', null, null); //初始化模糊搜索方法
					}
				}
			});
		}

		function queryDetail() {
			$.ajax({
				type: "GET",
				url: "../../api/check/rule/detail",
				data: {
					company: company,
					id: id,
				},
				success: function (result) {
					if (result.stat !== 200) return;

					$("#check_item").val(result.data.check_item);
					$("#target_table").val(result.data.target_table);
					$("#risk_market_item").val(result.data.risk_market_item);
					$("#problem_type").val(result.data.problem_type);
					$("#db").val(result.data.db);
					// $("#db").selectpicker({noneSelectedText: result.data.db});
					// $("#check_sql").val(result.check_sql);
					// editor.replaceSelection(result.check_sql);
					$("#note").val(result.data.note);
					$("#status").val(result.data.status);

					$("#problem_type").selectpicker("refresh");
					$("#db").selectpicker("refresh");
					$("#status").selectpicker("refresh");

					restore(result.data);
				}
			})
		}

		// 恢复状态
		function restore(data) {
			let leftAddBtn = $('.rule-wrapper-left').children('div:last-child').find('button');
			let rightAddBtn = $('.rule-wrapper-right').children('div:last-child').find('button');

			data.denominator.forEach((v, i) => {
				if (i > 0) {
					addRightItem(rightAddBtn, v).setValue(v.check_sql);
				} else {
					let textarea = rightAddBtn.parent().prev()[0].querySelector('textarea');
					let rightEditor = initEditor(textarea);
					rightEditor.id = v.id;
					rightEditor.setValue(v.check_sql);
					editor.right.push(rightEditor);
				}
				$('.rule-wrapper-right [name=t_name]').each(function () {
					$(this).val(v.t_name);
				});
				// $('.rule-wrapper-right [name=c_name]').each(function () {
				// 	$(this).val(v.c_name);
				// });
				$('.rule-wrapper-right [name=effective]').each(function () {
					$(this).val(v.effective == 1 ? '已启用' : '已停用');
					$(this).selectpicker('refresh');
				});
			});

			data.numerator.forEach((v, i) => {
				if (i > 0) {
					addLeftItem(leftAddBtn, v).setValue(v.check_sql);
				} else {
                    let textarea = leftAddBtn.parent().prev()[0].querySelector('textarea');
                    let leftEditor = initEditor(textarea);
                    leftEditor.id = v.id;
                    leftEditor.setValue(v.check_sql);
                    editor.left.push(leftEditor);
                }
			});
			$('.rule-wrapper-left [name=t_name]').each(function (i) {
				$(this).val(data.numerator[i].t_name);
			});
			// $('.rule-wrapper-left [name=c_name]').each(function (i) {
			// 	$(this).val(data.numerator[i].c_name);
			// });
			$('.rule-wrapper-left [name=effective]').each(function (i) {
				$(this).val(data.numerator[i].effective == 1 ? '已启用' : '已停用');
				$(this).selectpicker('refresh');
			});
			$('.rule-wrapper-left [name=denominator]').each(function (i) {
				$(this).val(data.numerator[i].denominator_order);
				$(this).selectpicker('refresh');
			});

			let leftChildren = $('.rule-wrapper-left').children();
			let rightChildren = $('.rule-wrapper-right').children();
			leftChildren.each(function(index) {
				if (index != leftChildren.length - 1) { // 不是最后一个，最后一个是按钮
					$(this).attr('id', data.numerator[index].id);
				}
			});
			rightChildren.each(function(index) {
				if (index != rightChildren.length - 1) { // 不是最后一个，最后一个是按钮
					$(this).attr('id', data.denominator[index].id);
				}
			});
		}

		// popover气泡提示窗
		function setPopover() {
			$("[data-toggle='popover']").popover({
				html : true,
				placement: "right",
				trigger: "hover focus",
				container: "body",
				title: "说明",
				delay:{show:100, hide:200},
				content: "<ul>\
			<li>完整性：主要包括实体缺失、属性缺失、记录缺失和字段值缺失四个方面；</li>\
			<li>准确性：一个数据值与设定为准确的值之间的一致程度，或与可接受程度之间的差异；</li>\
			<li>合理性：主要包括格式、类型、值域和业务规则的合理有效；</li>\
			<li>一致性：系统之间的数据差异和相互矛盾的一致性，业务指标统一定义，数据逻辑加工结果一致性；</li>\
			<li>及时性：数据仓库ETL、应用展现的及时和快速性，Jobs运行耗时、运行质量、依赖运行及时性。</li>\
			</ul>"
			});
			$("[data-toggle='popover1']").popover({
				html : true,
				placement: "right",
				trigger: "hover focus",
				container: "body",
				title: "说明",
				delay:{show:100, hide:200},
				content: "<ul>\
			<li>需要设置两个值,总的|问题数据</li>\
			</ul>"
			});
		};

		// 获取问题分类的列表
		function getProblemType(cb) {
			$.ajax({
				type: "post",
				contentType: 'application/json',
				url: "../../api/backend/aa10_query",
				data: JSON.stringify({category: 'quality'}),
				success: function (result) {
					if (result.stat == 200) {
						result.data.forEach(v => {
							$('#problem_type').append(`<option value="${v.dm}">${v.cmc}</option>`);
						});
						$("#problem_type").selectpicker("refresh");
						cb();
					}
				}
			})
		}

		// 初始化CodeMirror编辑框
		function initEditor(dom) {
			return CodeMirror.fromTextArea(dom, {
				lineNumbers: true,
				autofocus: false,
				mode: 'text/x-plsql',
				theme: 'eclipse',
				matchBrackets: true,
				autoCloseBrackets: true,
				extraKeys: {
					"Ctrl": "autocomplete"
				},
			});
		}

		function QueryDB(){
			$.ajax({
				type: "GET",
					url: "../../api/backend/database/query",
					data: {},
					success: function (result) {
						result.data.db_type.forEach((item, index) => {
							$("#db").append($(`<option value="${result.data.rowid[index]}">${result.data.name[index]} | ${item}</option>`));
						});
						$("#db").selectpicker("refresh");
					}
			})
		}

		function Commit(){
			if (!validate()) return;

			let leftNameList = $('.rule-wrapper-left [name=t_name]').map(function() {return $(this).val()}).get();
			let rightNameList = $('.rule-wrapper-right [name=t_name]').map(function() {return $(this).val()}).get();
			// let leftFieldList = $('.rule-wrapper-left [name=c_name]').map(function() {return $(this).val()}).get();
			// let rightFieldList = $('.rule-wrapper-right [name=c_name]').map(function() {return $(this).val()}).get();
			let leftStatusList = $('.rule-wrapper-left [name=effective]').map(function() {return $(this).val()}).get();
			let rightStatusList = $('.rule-wrapper-right [name=effective]').map(function() {return $(this).val()}).get();
			let bindList = $('.rule-wrapper-left [name=denominator]').map(function() {return $(this).val()});
			let leftSqlList = editor.left.map(item => item.getValue());
			let rightSqlList = editor.right.map(item => item.getValue());
			//
			let type = $("#problem_type").val();
			let data = {
				source_system:	company,
				check_item: 	$('#check_item').attr('pk_id'),
				target_table: 	$("#target_table").val(),
				risk_market:	$("#risk_market").val(),
				problem_type:	type === '-- 请选择 --' ? '' : type,
				db: 			$("#db").val(),
				note: 			$("#note").val(),
				status: 		$("#status").val(),
				numerator: 	leftNameList.map((v, i) => {
					let obj = {
						category_order: i + 1,
						t_name: v,
						// c_name: leftFieldList[i],
						c_name: '',
						check_sql: leftSqlList[i],
						effective: leftStatusList[i] === '已启用' ? 1 : 0,
						denominator_order: +bindList[i]
					};
					obj = id == 'null' ? obj : { ...obj, id: editor.left[i].id };
					return obj;
				}),
				denominator: rightNameList.map((v, i) => {
					let obj = {
						category_order: i + 1,
						t_name: v,
						// c_name: rightFieldList[i],
						c_name: '',
						check_sql: rightSqlList[i],
						effective: rightStatusList[i] === '已启用' ? 1 : 0
					};
					obj = id == 'null' ? obj : { ...obj, id: editor.right[i].id };
					return obj;
				})
			};

			if(id == 'null') { // 新增检核规则
				createRule(data);
			} else { // 更新检核规则
				updateRule(data);
			}
		}

		function validate() {
			let globalform = initGlobalFormValidator();
			let loacalFroms = initLocalFormValidator();

			let globalformValid = globalform.data('bootstrapValidator').validate().isValid();
			let loacalFromsValid = true;

			loacalFroms.each(function () {
				let item = $(this).data('bootstrapValidator').validate();
				loacalFromsValid = loacalFromsValid && item.isValid();
			});

			return globalformValid && globalformValid;
		}

		function initGlobalFormValidator() {
			let form = $("#form");
			$("#form").bootstrapValidator({
				excluded : [':disabled'],
				fields: {
					target_table: {
						validators: {
							notEmpty: {
								message: '目标表不能为空'
							}
						}
					},
					problem_type: {
						validators: {
							notEmpty: {
								message: '问题分类不能为空'
							},
							callback: {
								message: '请选择问题分类',
								callback: function(value, validator) {
									return value == '-- 请选择 --' ? false : true;
								}
							}
						}
					}
				}
			});
			return form;
		}

		function initLocalFormValidator() {
			let leftForms = $(".rule-wrapper-left form");
			let rightForms = $(".rule-wrapper-right form");
			let localForms = $([...leftForms, ...rightForms]);
			localForms.each(function() {
				$(this).bootstrapValidator({
					excluded : [':disabled'],
					fields: {
						t_name: {
							validators: {
								notEmpty: {
									message: '表名不能为空'
								}
							}
						},
						// c_name: {
						// 	validators: {
						// 		notEmpty: {
						// 			message: '字段名不能为空'
						// 		}
						// 	}
						// }
					}
				});
			});
			return localForms;
		}

		function createRule(data) {
			$.ajax({
				type: "POST",
				url: "../../api/check/rule/add",
				contentType: 'application/json',
				data: JSON.stringify(data),
				success: function (data) {
					if (data.stat == 200) {
						swal({
							text: "检核规则新增成功",
							icon: "success",
							buttons: false,
							timer: 1000
						});
						parent.window.renderTable({refresh: true});
						setTimeout(() => {
							window.parent.hideModal();
						}, 1000);
					} else {
						swal({
							title: '新增失败！',
							text: data.msg,
							icon: "error",
						});
					}
				},
				error: function (e) {
					console.error(e)
				}
			})
		}

		function updateRule(data) {
			$.ajax({
				type: "POST",
				url: "../../api/check/rule/update",
				contentType: 'application/json',
				data: JSON.stringify({id: id, delete_ids: delete_ids, ...data}),
				success: function (data) {
					if (data.stat == 200) {
						swal({
							text: "检核规则修改成功",
							icon: "success",
							buttons: false,
							timer: 1000
						});
						parent.window.renderTable({refresh: true});
						setTimeout(() => {
							window.parent.hideModal();
						}, 1000);
					} else {
						swal({
							title: '更新失败！',
							text: data.msg,
							icon: "error",
						});
					}
				},
				error: function (e) {
					console.error(e);
				}
			})
		}

		function addLeftItem(_this, v) {
			let leftEditor = addItem(_this, 'left');
			if (v) {
				leftEditor.id = v.id;
			}
			editor.left.push(leftEditor);
			let formGroup = $('.rule-wrapper-left .form-group');
			$($(formGroup[formGroup.length - 1]).find('li')[0]).attr('class', 'selected');
			return leftEditor;
		}

		function addRightItem(_this, v) {
			let rightEditor = addItem(_this, 'right');
			rightEditor.id = v.id;
			editor.right.push(rightEditor);
			let rightItemCount = $('.rule-wrapper-right').children().length - 1;
			let select = $('.rule-wrapper-left').find('[name=denominator]');
			select.next().each(function() {
				let options = '', lis = '';
				let selectedIndex = $(this).find('ul [class=selected]').attr('data-original-index');
				for (let i = 1; i < rightItemCount + 1; i ++) {
					options += `<option value="${i}">${i}</option>`;
					lis += `<li data-original-index="${i - 1}" class="${selectedIndex == i ? 'selected' : ''}">
								<a tabindex="0" class="" data-normalized-text="<span class='text'>${i}</span>" data-tokens="null">
									<span class="text">${i}</span>
									<span class="glyphicon glyphicon-ok check-mark"></span>
								</a>
							</li>`;
				}
				$(this).find('ul').html(lis);
				select.html(options);
				select.selectpicker("refresh");
			});
			return rightEditor;
		}

		function addItem(_this, position) {
			let leftItemCount = $('.rule-wrapper-left').children().length;
			let rightItemCount = $('.rule-wrapper-right').children().length;

			let bind = '';
			if (position === 'left') {
				bind = getRightBind(rightItemCount - 1);
			}
			let child = `
				<div>
					<form class="navbar-form form-inline" style="background: #fff;padding: 10px;">
						<div class="form-group">
							<div class="inline-block">
								<label>序号: </label>
							</div>
							<div class="inline-block order">${position === 'left' ? leftItemCount : rightItemCount}</div>
						</div>
						<div class="form-group">
							<div class="inline-block">
								<label>子规则名</label>
							</div>
							<div class="inline-block">
								<input name="t_name" type="text" class="form-control" autocomplete="off">
							</div>
						</div>
						<!--<div class="form-group">-->
							<!--<div class="inline-block">-->
								<!--<label>字段名</label>-->
							<!--</div>-->
							<!--<div class="inline-block">-->
								<!--<input name="c_name" type="text" class="form-control" autocomplete="off">-->
							<!--</div>-->
						<!--</div>-->
						<div class="form-group">
							<div class="inline-block">
								<label>状态</label>
							</div>
							<div class="inline-block" style="width: 81px">
								<select class="selectpicker" name="effective">
									<option value="已启用">已启用</option>
									<option value="已停用">已停用</option>
								</select>
							</div>
						</div>
						${bind}
						<div class="form-group" style="float: right; margin-right: 0;">
							<button class="btn btn-danger btn-sm" onclick="deleteItem(this, '${position}')">删除</button>
						</div>
					</form>
					<div>
						<textarea name="code" type="text" class="form-control"></textarea>
					</div>
				</div>
			`;
			$(_this).parent().before(child);	// 插入
			$(_this).parent().parent().find('select').each(function() {
				$(this).selectpicker("refresh");
			});
			$('.rule-wrapper-left').children().each(function(index) {
				$(this).attr('index', index);
			});
			return initEditor($(_this).parent().prev()[0].querySelector('textarea'));	// 初始化编辑器
		}

		function getRightBind(count) {
			let options = '';
			for (let i = 1; i < count + 1; i ++) {
				options += `<option value="${i}">${i}</option>`;
			}
			return `
				<div class="form-group">
					<div class="inline-block">
						<label>绑定分母</label>
					</div>
					<div class="inline-block" style="width: 80px">
						<select class="selectpicker" name="denominator">
							${options}
						</select>
					</div>
				</div>
			`;
		}

		function deleteItem(_this, position) {
			let item = $(_this).parent().parent().parent();
			let wrapper = item.parent();	// rule-wrapper-left rule-wrapper-right
			let currentIndex = item.attr('index');
			let currentId = item.attr('id');
			item.remove();
			$(".rule-wrapper-" + position).children().each(function(index) {
				$(this).attr('index', index)
			});
			wrapper.find('.order').each(function(index) {
				$(this).html(index + 1);
			});
			if (currentId !== undefined) {
				editor[position].splice(currentIndex, 1);
				delete_ids.push(currentId);
			}
		}
	</script>

</body>

</html>